import axios from "axios";
import errorCode from "./errorCode.js";
import { ElMessage,ElMessageBox } from 'element-plus'
import router from "@/router";
import { getToken } from "@/utils/auth";
import { clearAllCache } from './globalWay.js'; 
import { filterObject,isEmptyObject} from './common.js'

let msgRef = null;
//登录接口所需特殊秘钥
const loginSecretKey = import.meta.env.VITE_APP_LOGINSECRETKEY;

const service = axios.create({
    timeout: 60000,
    withCredentials: true,
    baseURL:  import.meta.env.VITE_APP_BASEURL,
    validateStatus: function (status) {
      return status >= 200 && status <= 500; // 默认的
    },
});
export let cancelRequest = (cancel) => {
  if((cancel??'') === '')return;
  console.warn(cancel)

}
// request拦截器
service.interceptors.request.use(
    async config => {
      // 判断是否需要token
      const token = getToken()
      if (!config.noToken) {
        config.headers.Authorization = `Bearer ${token}`;
        // config.headers.Authorization = `Bearer eyJraWQiOiJmNzUzMDMzNi0zZDAzLTQyOTMtODlhZS0yNzFmZTAxMmQ4NjMiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZCI6InN5c3RlbS1jbGllbnQiLCJuYmYiOjE2OTgxMzIyMjAsInNjb3BlIjpbImFsbCIsInNjb3BlOnN5c3RlbSJdLCJpc3MiOiJodHRwOi8vMTAuMjMzLjY2LjExMCIsImV4cCI6MTY5ODIxODYyMCwiaWF0IjoxNjk4MTMyMjIwLCJqdGkiOiJmMTk5YzIwMy1jMmQ2LTRjMmUtOGRiZS03MTQ1NzNhYTI5NmQifQ.Swj3eKoFkCClFgl-m3XZpb9ufPRkTGQa6UsoVm-9RP6SovKJltxJb1ZpISJ6FakU_XzIwg0wBqmfGCpgrWZkbeRlT1cWlKJ90NFw93o4J0z76Wmwr8Oh4EsZoOKtQk9ceLE9D1RN3mKQmp_4e-7yk6uqkPFyTqzAhP5folBcQG88IAuQ9rsOAq-FNwp_Og6vQJKH3ToTkjLedVC4t1raqhiSL2H6FADHGyKoCli8dQUwUW3ERDxfQ1H5eBwEf31ngUYH33_3Kxzcn4b6WKnalaEwmz_rG2rgjprnuaL2MfZfnC9CJKovnZQ2lv4_OJ64OLYm_AEjsL-o-phQmn-MLA`;
      }
      //判断是否是登录接口
      if (config.loginApi) {
        config.headers.Authorization = loginSecretKey;
      }
      // get请求
      if (config.method === "get") {
        config.params = filterObject(config.params);
      }
      // post请求
      if (config.method === "post") {
        config.data = filterObject(config.data);
        if(isEmptyObject(config.data)){
          config.data = undefined;
        }  
      }
      
      let cancel
      // 设置cancelToken对象 noCancelToken 为true时不设置，默认设置
      if(!config.noCancelToken){
        config.cancelToken =  new axios.CancelToken(function(c) {
            cancel = c;
            cancelRequest = c;
        })
      }
      return config;
    },
    (error) => {
      return Promise.reject(new Error(error));
    }
  );
  
  // response拦截器
  service.interceptors.response.use(
    res => {
      const status = Number(res.status) || 200;
      const message = res.data.msg || errorCode[status] || errorCode["default"];


      let data = new Object();
      if (status === 401 || res.data.code === 20001) {
        if(msgRef != null){
          msgRef.close();
        }
        msgRef = ElMessage({
            message: '授权已过期，请重新登录',
            type: "error",
        })
        clearAllCache();
        setTimeout(()=>{
          router.replace('/login');
        },1000)
        
        return;
      } else if (status === 200 && (res.data.code === 0 || res.data.code === 200)) {
        data = res.data.data;
      }else {
        if(res && res.data && res.data.code == 1000){
          ElMessageBox({
            type: 'warning',
            title: '提示',
            showCancelButton: false,
            confirmButtonText:'确定',
            message:message,
            beforeClose: async (action, instance, done) => {
              done()
            },
          })
        }else{
          ElMessage({
            message: message,
            type: "error",
          });

        }
        return Promise.reject(new Error(message));
      }
      return data;
    },
    error => {
      console.log(error,666);
      //网络超时异常处理
      if(error.code === 'ECONNABORTED' || error.message ===   "Network Error" ||  error.message.includes("timeout")){
          if(msgRef != null){
            msgRef.close();
          }  
          msgRef = ElMessage({
              message: '请求超时，请稍后再试',
              type: "error",
          })
      }
      return Promise.reject(error);
    }
  );
  
  export default service;